﻿using MediatR;
using PublicClass;
using S.RBAC.Domain.Model;
using S.RBAC.Infrastructure.Interface;
using S.RBAC.Read.Api.Application.Command.RoleCommand;
using System.Collections.Generic;

namespace S.RBAC.Read.Api.Application.CommandHandlers.RoleHandler
{
    public class RoleSelectCommandHandler : IRequestHandler<RoleSelectCommand, PageInfo<Role>>
    {
        protected readonly IRoleRepository _role;

        public RoleSelectCommandHandler(IRoleRepository role)
        {
            _role = role;
        }

        public async Task<PageInfo<Role>> Handle(RoleSelectCommand request, CancellationToken cancellationToken)
        {
            var info = await _role.GetRoleInfo(t => t.IsDel == false);

            if (!string.IsNullOrWhiteSpace(request.RoleName))
            {
                info = info.Where(t => t.RoleName.Contains(request.RoleName)).ToList();
            }

            //总行数
            int totalCount = info.Count;
            //总页数
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            //分页
            info = info.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return new PageInfo<Role> { totalCount = totalCount, pageCount = pageCount, datas = info };
        }
    }
}
